package cn.hashq.netpoststation.runner;

import cn.hashq.netpoststation.entity.Client;
import cn.hashq.netpoststation.entity.PortMap;
import cn.hashq.netpoststation.service.ClientManagerService;
import cn.hashq.netpoststation.service.PortMapManagerService;
import cn.hashq.netpoststation.util.NettyUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 启动已有端口映射
 *
 * @author HashQ
 * @since 1.0
 */
@Slf4j
@Component
public class PortMapRunner implements CommandLineRunner {

    @Resource
    private PortMapManagerService portMapService;

    @Resource
    private ClientManagerService clientService;

    @Resource
    private NettyUtil nettyUtil;

    @Override
    public void run(String... args) throws Exception {
        List<Client> clients = clientService.list();
        clients.forEach(e -> {
            if (e.getStatus().compareTo(1) == 0) {
                startPortMap(e.getClientId());
            }
        });
    }

    private void startPortMap(Long clientId) {
        List<PortMap> portMaps = portMapService.list(Wrappers.<PortMap>lambdaQuery().eq(PortMap::getClientId, clientId));
        portMaps.stream().forEach(e -> {
            nettyUtil.startPortMap(e);
        });
    }



}
